package org.summer.lawyer.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import org.summer.common.core.constant.Constants;
import org.summer.common.core.utils.MapstructUtils;
import org.summer.common.mybatis.core.page.PageQuery;
import org.summer.common.mybatis.core.page.TableDataInfo;
import org.summer.common.satoken.utils.LoginHelper;
import org.summer.lawyer.domain.SpuComment;
import org.summer.lawyer.domain.bo.spucomment.SpuCommentBo;
import org.summer.lawyer.domain.bo.spuorder.SpuOrderBo;
import org.summer.lawyer.domain.vo.spucomment.SpuCommentVo;
import org.summer.lawyer.domain.vo.spuorder.SpuOrderVo;
import org.summer.lawyer.domain.vo.spuorderassign.SpuOrderAssignVo;
import org.summer.lawyer.domain.vo.wxuser.WxUserVo;
import org.summer.lawyer.event.SpuCommentEvent;
import org.summer.lawyer.mapper.SpuCommentMapper;
import org.summer.lawyer.service.*;
import org.summer.lawyer.util.ParamsUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 商品评价信息Service业务层处理
 *
 * @author summer
 * @date 2024-06-21
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SpuCommentServiceImpl extends ServiceImpl<SpuCommentMapper, SpuComment> implements ISpuCommentService, ApplicationEventPublisherAware {

    private final ILawFirmService lawFirmService;
    private final IWxUserService wxUserService;
    private final ISpuOrderService spuOrderService;
    private final ISpuOrderAssignService spuOrderAssignService;

    /**
     * 查询商品评价信息
     *
     * @param id 主键
     * @return 商品评价信息
     */
    @Override
    public SpuCommentVo selectSpuCommentVoById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询商品评价信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 商品评价信息分页列表
     */
    @Override
    public TableDataInfo<SpuCommentVo> selectPageList(SpuCommentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SpuComment> lqw = buildQueryWrapper(bo);
        Page<SpuCommentVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
//        if(CollUtil.isNotEmpty(result.getRecords())){
//            for (SpuCommentVo record : result.getRecords()) {
//
//            }
//        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的商品评价信息列表
     *
     * @param bo 查询条件
     * @return 商品评价信息列表
     */
    @Override
    public List<SpuCommentVo> selectSpuCommentVoList(SpuCommentBo bo) {
        LambdaQueryWrapper<SpuComment> lqw = Wrappers.lambdaQuery();
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SpuComment> buildQueryWrapper(SpuCommentBo bo) {
        Map<String, Object> params = ParamsUtil.getParams(bo.getParams());
        LambdaQueryWrapper<SpuComment> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getWxUserId() != null, SpuComment::getWxUserId, bo.getWxUserId());
        lqw.like(StrUtil.isNotBlank(bo.getNickname()), SpuComment::getNickname, bo.getNickname());
        lqw.like(StrUtil.isNotBlank(bo.getOrderNumber()), SpuComment::getOrderNumber, bo.getOrderNumber());
        lqw.like(StrUtil.isNotBlank(bo.getLawFirmName()), SpuComment::getLawFirmName, bo.getLawFirmName());
        lqw.eq(StrUtil.isNotBlank(bo.getAnonymous()), SpuComment::getAnonymous, bo.getAnonymous());
        lqw.eq(bo.getOrderId() != null, SpuComment::getOrderId, bo.getOrderId());
        lqw.eq(bo.getOrderItemId() != null, SpuComment::getOrderItemId, bo.getOrderItemId());
        lqw.eq(bo.getSpuId() != null, SpuComment::getSpuId, bo.getSpuId());
        lqw.like(StrUtil.isNotBlank(bo.getSpuName()), SpuComment::getSpuName, bo.getSpuName());
        lqw.eq(bo.getLawFirmId() != null, SpuComment::getLawFirmId, bo.getLawFirmId());
        lqw.eq(StrUtil.isNotBlank(bo.getReviewTag()), SpuComment::getReviewTag, bo.getReviewTag());
        lqw.eq(StrUtil.isNotBlank(bo.getReplyStatus()), SpuComment::getReplyStatus, bo.getReplyStatus());
        lqw.eq(bo.getReplyUserId() != null, SpuComment::getReplyUserId, bo.getReplyUserId());
        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), SpuComment::getStatus, bo.getStatus());
        lqw.eq(StrUtil.isNotBlank(bo.getVisible()), SpuComment::getVisible, bo.getVisible());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null, SpuComment::getReviewTime, params.get("beginTime"), params.get("endTime"));
        lqw.orderByDesc(SpuComment::getId);
        return lqw;
    }

    /**
     * 新增商品评价信息
     *
     * @param bo 商品评价信息
     * @return 是否新增成功
     */
    @DSTransactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertByBo(SpuCommentBo bo) {
        SpuComment add = MapstructUtils.convert(bo, SpuComment.class);
        validEntityBeforeSave(add);
        //获取评论用户信息
        WxUserVo wxUser = wxUserService.selectWxUserVoById(bo.getWxUserId());
        if (wxUser != null) {
            add.setNickname(wxUser.getNickname());
            add.setAvatar(wxUser.getAvatar());
            add.setAnonymous("0");
            add.setPhoneNumber(wxUser.getPhoneNumber());
        }
        //订单信息
        if (add.getOrderId() != null) {
            SpuOrderVo spuOrderVo = spuOrderService.selectSpuOrderVoById(bo.getOrderId());
            if (spuOrderVo != null) {
                add.setOrderItemId(spuOrderVo.getOrderItemId());
                add.setOrderNumber(spuOrderVo.getOrderNumber());
                add.setSpuId(spuOrderVo.getSpuId());
                add.setSpuName(spuOrderVo.getSpuName());
                if (add.getLawFirmId() == null) {
                    //查询派单信息
                    SpuOrderAssignVo orderAssignVo = spuOrderAssignService.selectSpuOrderAssignVoBySpuOrderId(spuOrderVo.getOrderId());
                    if (orderAssignVo != null) {
                        add.setLawFirmId(orderAssignVo.getLawFirmId());
                        add.setLawFirmLogo(orderAssignVo.getLawyerAvatar());
                        add.setLawFirmName(orderAssignVo.getLawFirmName());
                    }
                }
                //完成订单评价
                SpuOrderBo spuOrderBo = new SpuOrderBo();
                spuOrderBo.setOrderId(add.getOrderId());
                spuOrderService.completedReview(spuOrderBo);
            }

        }
        add.setReviewTime(DateUtil.date());
        add.setStatus("1");
        add.setVisible("1");
        add.setReplyStatus("0");
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改商品评价信息
     *
     * @param bo 商品评价信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SpuCommentBo bo) {
        SpuComment update = MapstructUtils.convert(bo, SpuComment.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SpuComment entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除商品评价信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void passedSpuComment(SpuCommentBo bo) {
        SpuCommentVo commentVo = selectSpuCommentVoById(bo.getId());
        SpuComment comment = new SpuComment();
        comment.setId(bo.getId());
        comment.setStatus("1");
        comment.setUpdateTime(DateUtil.date());
        if (LoginHelper.getUserId() != null) {
            comment.setUpdateBy(LoginHelper.getUserId());
        }
        LambdaUpdateWrapper<SpuComment> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(SpuComment::getId, bo.getId());
        baseMapper.update(comment, updateWrapper);
        //评价完成事件
        applicationEventPublisher.publishEvent(new SpuCommentEvent(this, commentVo.getLawFirmId()));
    }

    @Override
    public Integer countCommentByDay(SpuCommentBo bo) {
        Date now = DateUtil.date();
        Date beginTime = DateUtil.beginOfDay(now);
        Date endTime = DateUtil.endOfDay(now);
        QueryWrapper<SpuCommentBo> queryWrapper = Wrappers.query();
        queryWrapper.eq("sc.del_flag", Constants.DEL_FLAG_NOT_DEL);
        queryWrapper.eq("sc.wx_user_id", bo.getWxUserId());
        queryWrapper.eq("sc.law_firm_id", bo.getLawFirmId());
        // queryWrapper.eq("lf.law_firm_type", bo.getLawFirmType());
        queryWrapper.between("sc.review_time", beginTime, endTime);
        return baseMapper.countCommentByDay(queryWrapper);
    }

    @Override
    public void calRating(Long lawFirmId) {
        QueryWrapper<SpuComment> lqw = Wrappers.query();
        lqw.select(" coalesce(avg(overall_rating),0) as avgRating ");
        lqw.eq("law_firm_id", lawFirmId);
        lqw.eq("status", "1");
        lqw.eq("del_flag", Constants.DEL_FLAG_NOT_DEL);
        List<Map<String, Object>> mapList = baseMapper.selectMaps(lqw);
        if (CollUtil.isNotEmpty(mapList)) {
            for (Map<String, Object> map : mapList) {
                BigDecimal rating = new BigDecimal(map.get("avgRating").toString());
                //保留2位小数，四舍五入
                rating = rating.setScale(2, RoundingMode.HALF_UP);
                lawFirmService.updateRating(lawFirmId, rating);
            }

        }
    }

    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
}
